﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Activities;

using CloudSoft.Workflows;

namespace ERPStore.Exporter.Workflows.Activities
{

	public sealed class GetProductStockList : CodeActivity
	{
		public InArgument<List<ERPStore.Models.Product>> ProductList { get; set; }
		public OutArgument<List<ERPStore.Models.ProductStockInfo>> ProductStockInfoList { get; set; }

		protected override void Execute(CodeActivityContext context)
		{
			var catalogService = context.GetService<ERPStore.Services.ICatalogService>();
			var productList = context.GetValue(ProductList);

			var productIdList = productList.Select(i => i.Id).Distinct();
			IList<ERPStore.Models.ProductStockInfo> stockList = null;
			int retryCount = 0;
			while (true)
			{
				try
				{
					stockList = catalogService.GetProductStockInfoList(productIdList);
					break;
				}
				catch(Exception ex)
				{
					if (retryCount > 5)
					{
						ex.Data.Add("RetryCount", "5 * 5s");
						throw (ex);
					}
					System.Threading.Thread.Sleep(5 * 1000);
					retryCount++;
				}
			}

			context.SetValue(ProductStockInfoList, stockList);

			context.ReportProgress(string.Format("found {0} product with stock", stockList.Count));
		}
	}
}
